﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基础信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>退休信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_PersonId_FormItem"
										prop="Entity.PersonId"
										:rules="[{ required: true, message: '退休员工为必填项', trigger: 'change' }]"
									>
										<template #label>
											<WtmLabelTooltip label="退休员工" tooltip="选择申请退休的员工" />
										</template>
										<WtmPersonSelector
											v-model="stateData.vmModel.Entity.PersonId"
											:prefill-person="{
												ID: stateData.vmModel.Entity.PersonId,
												Name: stateData.vmModel.Entity.Name,
												StaffNo: stateData.vmModel.Entity.StaffNo,
											}"
											@change="onPersonSelected"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_RetireDate_FormItem"
										prop="Entity.RetireDate"
										:rules="[{ required: true, message: '退休日期为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="退休日期" tooltip="退休日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.RetireDate" clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_ResignType_FormItem"
										prop="Entity.ResignType"
										:rules="[{ required: true, message: '离职类型为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="离职类型" tooltip="离职类型" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.ResignType" clearable class="width100">
											<el-option v-for="item in RESIGN_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="Entity_Describe_FormItem" prop="Entity.Describe">
										<template #label>
											<WtmLabelTooltip label="退休说明" tooltip="退休说明" />
										</template>
										<el-input type="textarea" v-model="stateData.vmModel.Entity.Describe" clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="true" :auth="false" placeholder="选取人员后带入" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" label="所属部门" :disabled="true" :auth="false" />
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { SysHrRetireRequestBillApi as api } from '/@/views/hr/syshrretirerequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysHrRetireRequestBillVm } from '/@/views/hr/syshrretirerequestbill/api/interface';
import { IViewModel } from '/@/types/common';

/**
 * ===== 常量定义区域 =====
 * 统一管理业务常量，便于维护和复用
 */

/** 单据状态枚举 */
const BILL_STATUS = {
	DRAFT: '草稿', // 草稿状态，可编辑
	FORMAL: '正文', // 正式状态，不可编辑
} as const;

/** 工作流状态枚举 */
const WORKFLOW_STATUS = {
	PENDING: '待提交', // 初始状态，等待提交
	SUBMITTING: '提交中', // 正在提交流程
	IN_AUDIT: '审核中', // 审批流程中
} as const;
const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;
/** 离职类型下拉选项 */
const RESIGN_TYPE_OPTIONS = [
	{ value: '正常退休', label: '正常退休' }, // 达到法定退休年龄
	{ value: '提前退休', label: '提前退休' }, // 特殊工种或身体原因
	{ value: '内退', label: '内退' }, // 内部退休
	{ value: '病退', label: '病退' }, // 因病提前退休
	{ value: '特殊工种退休', label: '特殊工种退休' }, // 井下、高温、有毒有害等
	{ value: '因公伤残退休', label: '因公伤残退休' }, // 工伤致残退休
	{ value: '困难企业职工退休', label: '困难企业职工退休' }, // 破产企业等
] as const;

/** 按钮文本配置 */
const BUTTON_TEXTS = {
	SAVE: '保存', // 保存按钮文本
	SUBMIT: '提交', // 提交按钮文本
	CLOSE: '关闭', // 关闭按钮文本
	AGREE: '同意', // 同意按钮文本
	REJECT: '取消', // 按钮文本
} as const;

/**
 * ===== 组件实例和基础配置 =====
 */

/** 组件实例，用于访问组件上下文 */
const ci = getCurrentInstance() as ComponentInternalInstance;

/** 页面加载状态控制 */
const loading = ref(false);

/** 表单引用 */
const formRef = ref();

/** 当前激活的标签页 */
const activeTab = ref('main');

/**
 * ===== 响应式状态数据 =====
 */

/** 编辑页面数据模型 */
const stateData = reactive<IViewModel<ISysHrRetireRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null, // 记录ID
			PersonId: null, // 员工ID
			StaffNo: null, // 员工工号
			Name: null, // 员工姓名
			RetireDate: null, // 退休日期
			ResignType: null, // 离职类型
			Describe: null, // 退休说明
			Approver: null, // 审批人
			ApprovalTime: null, // 审批时间
			GroupId: null, // 所属部门ID
			BillCode: null, // 单据编号
			BillStatus: null, // 单据状态
			WorkflowStatus: null, // 工作流状态
			Remark: null, // 备注
			OrgId: null, // 所属公司ID
		},
		ActionName: null, // 当前操作名称
		IsMyApprove: null, // 是否我的审批
		Remark: null, // 审批原因
	},
});

/**
 * ===== 计算属性 =====
 * 根据响应式数据动态计算衍生值
 */

/** 是否处于审核中状态 */
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);

/** 是否可以提交 - 草稿状态且未进入审核流程 */
const canSubmit = computed(
	() =>
		stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT &&
		(!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING)
);

/** 是否可以审批 - 有审批权限且处于审核中状态 */
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove && isInAudit.value);

/**
 * ===== 工具函数 =====
 */

/** 统一的成功处理函数 - 处理操作成功后的通用逻辑 */
const handleSuccess = (isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh'); // 通知父组件刷新数据
		closeDialog(); // 关闭对话框
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh'); // 通知父组件刷新数据
		// 保存后不关闭弹窗
	}
	loading.value = false;
};

/** 统一的错误处理函数 - 处理API调用失败等错误情况 */
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

/** 公共的API请求处理函数 - 处理表单验证和API调用的通用逻辑 */
const handleApiRequest = (apiCall: () => Promise<any>, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			apiCall()
				.then(() => handleSuccess(isSubmit))
				.catch(handleError);
		}
	});
};

/** 公共的审批处理函数 - 处理审批操作的通用逻辑 */
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then(() => handleSuccess(true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

/**
 * ===== 操作函数 =====
 */

/** 关闭对话框 */
const onClose = () => {
	closeDialog();
};

/** 保存操作 - 保存修改但不关闭对话框 */
const onSave = () => {
	handleApiRequest(() => api().edit(stateData.vmModel), false); // 保存后不关闭弹窗
};

/** 提交操作 - 提交审批流程并关闭对话框 */
const onSubmit = () => {
	if (!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING) {
		stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING; // 设置为提交中状态
	}
	handleApiRequest(() => api().edit(stateData.vmModel), true); // 提交后关闭弹窗
};

// 同意
const onAgree = () => {
	handleApproval(ACTIONS.AGREE);
};

// 拒绝
const onDeny = () => {
	handleApproval(ACTIONS.REJECT);
};

// // 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};

/**
 * ===== 数据初始化函数 =====
 */

/** 初始化页面数据 - 从路由参数或组件属性中获取记录ID */
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

/** 加载页面所需的所有数据 */
const loadPageData = async () => {
	// 并行加载部门数据和实体数据
	const [entityData] = await Promise.allSettled([api().get(stateData.vmModel.Entity.ID ?? '')]); // 获取实体详情数据

	// 处理成功的结果
	if (entityData.status === 'fulfilled') other.setValue(stateData.vmModel, entityData.value);
};

/**
 * ===== 生命周期钩子 =====
 */

/** 组件挂载时执行 - 初始化页面数据 */
onMounted(async () => {
	loading.value = true;
	initializePageData(); // 初始化页面参数

	try {
		await loadPageData(); // 加载页面数据
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false; // 无论成功失败都要关闭loading
		nextTick(() => {
			setupHeaderButtons(); // 设置头部按钮
		});
	}
});

/**
 * ===== 组件通信 =====
 */

/** 定义子组件向父组件传值/事件 */
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

/** 关闭弹窗 */
const closeDialog = () => {
	emit('closeDialog');
};

/** 设置对话框头部按钮 - 根据当前状态动态配置按钮显示 */
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !isInAudit.value, // 只有非审核状态才显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value && !isInAudit.value, // 只有可提交且非审核状态才显示提交按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示同意
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示拒绝
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true, // 始终显示关闭按钮
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
